import React, { useState, useContext, useEffect } from "react";
import { Modal, ModalBody, ModalHeader, Media, Input, Button, Row, Col } from "reactstrap";
import { CurrencyContext } from "../../../helpers/Currency/CurrencyContext";
import CartContext from "../../../helpers/cart";
import { addProductToCart, createSingleOrder } from "../../../api/api";
import { toast } from "react-toastify";
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js"
import { PayPalClientId } from "../../../components/constant/constants";
import Loading from "../../../components/common/Loading";

const DetailsWithPrice = ({ item, stickyClass, changeColorVar }) => {
  const [modal, setModal] = useState(false);
  const [payModelIsOpen, setPayModelIsOpen] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [checkoutTotal, setCheckoutTotal] = useState("");
  const [orderIds, setOrderIds] = useState([]);

  const CurContect = useContext(CurrencyContext);
  const symbol = CurContect.state.symbol;
  const toggle = () => setModal(!modal);
  const product = item;
  const context = useContext(CartContext);
  const stock = context.stock;
  const plusQty = context.plusQty;
  // const minusQty = context.minusQty;
  const quantity = context.quantity;
  const uniqueColor = [];
  const uniqueSize = [];

  const [qty, setQty] = useState(1);
  const [stockMsg, setStockMsg] = useState("Stock");
  const [payLoading, setPayLoading] = useState(true);

  // const changeQty = (e) => {
  //   // console.log(e.target.value)
  // };

  const addQty = () => {
    if (qty < product.product_num) {
      setQty(v => v + 1);
    }
    else {
      setStockMsg("Out Of Stock!");
    }
  }

  const minusQty = () => {
    if (qty > 1) {
      setQty(v => v - 1);
    }
  }

  const handleAddProductToCart = (dataitem) => {
    var user = localStorage.getItem("XYCLogin");
    if (user) {

      var input = {
        "product_id": dataitem.product_id,
        "quantity": `${qty}`,
        "user_guid": JSON.parse(user).user_guid
      };
      addProductToCart(input).then(res => {
        if (res.error_code == "2000") {
          toast.success(res.msg);
        }
        else {
          toast.warning(res.msg);
        }
      })
    }
    else {
      toast.error("Please Login To Shopping!")
    }
  }

  const handleBuyNow = (dataitem) => {
    var user = localStorage.getItem("XYCLogin");
    if (user) {
      var input = {
        "product_id": dataitem.product_id,
        "quantity": `${qty}`,
        "user_guid": JSON.parse(user).user_guid
      };
      setIsOpen(true);
      // TODO: 打开新Modal，进行结算，调用PayPal生成订单
    }
    else {
      toast.error("Please Login To Shopping!")
    }
  }

  const onCreateOrder = async (data, actions) => {
    return actions.order.create({
      purchase_units: [{
        amount: {
          currency_code: 'USD',
          value: checkoutTotal
        }
      }]
    })
  }

  const onApproveOrder = async (data, actions) => {
    const orderData = await actions.order?.capture();

    if (orderData?.status == 'COMPLETED') {
      await approveOrder({
        "payment_order_id": orderData?.id,
        "order_ids": orderIds
      }).then(res => {
        if (res.error_code == "2000") {
          toast.success("Checkout Succeed!");
          setPayModelIsOpen(false);
          location.reload();
        }
      })
    }
  }

  const confirmOrder = () => {
    setIsLoading(true);
    var list = [{
      "product_id": product.product_id,
      "quantity": qty.toString()
    }];
    // qtyList.map(item => {
    //   list.push({
    //     "product_id": product.product_id,
    //     "quantity": item.quantity
    //   });
    // });
    var json = {
      "order_list": list
    }
    createSingleOrder(json).then(res => {
      if (res.error_code != "2000") {
        setIsLoading(false);
        toast.error("Create Order Failed.")
      }
      else {
        setIsLoading(false);
        setCheckoutTotal(res.total_price);
        setOrderIds(res.order_ids);
        setIsOpen(false);
        setPayModelIsOpen(true);
      }
    });
  }

  useEffect(() => {
    if (qty <= product.product_num) {
      setStockMsg("Stock");
    }
  }, [qty])

  return (
    <>
      <Modal isOpen={payModelIsOpen} centered size="lg" style={{ width: 400 }}>
        <ModalHeader>Payment Provider
        </ModalHeader>
        <ModalBody>
          {payLoading && <Loading />}

          <div className="checkout-form">
            <div style={{ display: payLoading ? "none" : "inline" }}>
              <PayPalScriptProvider options={{ clientId: PayPalClientId }}>
                <PayPalButtons
                  createOrder={onCreateOrder}
                  onApprove={onApproveOrder}
                  // onError={onError}
                  onInit={() => setPayLoading(false)}
                  style={{ layout: "horizontal" }}
                />
              </PayPalScriptProvider>
            </div>
            <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setPayModelIsOpen(false); setIsLoading(false); }}>Cancel</Button>
          </div>
        </ModalBody>
      </Modal>
      <Modal isOpen={isOpen} centered size="lg" style={{ width: 600 }}>
        <ModalHeader >Order Confirm
        </ModalHeader>
        <ModalBody>
          <div className="checkout-form">
            <Row style={{ marginTop: 20 }}>
              <Col sm="12">
                <h3>{`Confirm payment? The total amount is `}<span style={{ color: 'red' }}>{symbol} {qty * product.product_price}</span></h3>
              </Col>
            </Row>

            <Row style={{ marginTop: 20 }}>
              <Col sm="6">
                <Button style={{ minWidth: '100%' }} onClick={() => { setIsOpen(false) }} disabled={isLoading}>Cancel</Button>
              </Col>
              <Col sm="6">
                <Button color="primary" style={{ minWidth: '100%' }} onClick={() => { confirmOrder() }} disabled={isLoading}>Confirm</Button>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      <div className={`product-right ${stickyClass}`}>
        <h2> {product.product_name} </h2>
        Detail Price
        <h4>
          {/* 可设置折扣金额 */}
          {/* <del>
            {symbol}
            {product.price}
          </del> */}
          {/* <span>{product.discount}% off</span> */}
        </h4>
        <h3>
          {symbol}
          {product.product_price}
        </h3>
        {/* {product.variants.map((vari) => {
          var findItem = uniqueColor.find((x) => x.color === vari.color);
          if (!findItem) uniqueColor.push(vari);
          var findItemSize = uniqueSize.find((x) => x === vari.size);
          if (!findItemSize) uniqueSize.push(vari.size);
        })} */}

        <div className="border-product">
          <h6 className="product-title">product details</h6>
          <p>{product.product_detail}</p>
        </div>
        <div className="product-description border-product">
          <span className="instock-cls">{stockMsg}</span>
          <h6 className="product-title">quantity</h6>
          <div className="qty-box">
            <div className="input-group">
              <span className="input-group-prepend">
                <button
                  type="button"
                  className="btn quantity-left-minus"
                  onClick={minusQty}
                  data-type="minus"
                  data-field=""
                >
                  <i className="fa fa-angle-left"></i>
                </button>
              </span>
              <Input
                type="text"
                name="quantity"
                disabled
                value={qty}
                // onChange={changeQty}
                className="form-control input-number"
              />
              <span className="input-group-prepend">
                <button
                  type="button"
                  className="btn quantity-right-plus"
                  onClick={addQty}
                  data-type="plus"
                  data-field=""
                >
                  <i className="fa fa-angle-right"></i>
                </button>
              </span>
            </div>
          </div>
        </div>
        <div className="product-buttons">
          <a
            href={null}
            className="btn btn-solid"
            style={{ display: "block", width: 240 }}
            onClick={() => handleAddProductToCart(product)}
          >
            add to cart
          </a>
          <Button disabled={isLoading} className="btn btn-solid" style={{ display: "block", marginTop: 20, width: 240 }} onClick={() => { handleBuyNow(product) }}>buy now</Button>
        </div>
        {/* <div className="border-product">
          <h6 className="product-title">share it</h6>
          <div className="product-icon">
            <MasterSocial />
          </div>
        </div> */}
        {/* <div className="border-product">
          <h6 className="product-title">Time Reminder</h6>
          <CountdownComponent />
        </div> */}
      </div>
    </>
  );
};

export default DetailsWithPrice;
